#include <SoftwareSerial.h>
int sensor_temp = A0;
int value_temp;
int sensor_light = A2;
int value_light;
int sensor_water = A1;
int value_water;
#define DEBUG //comment out to remove debug msgs
#define _baudrate 9600
#define _rxpin 0
#define _txpin 1
SoftwareSerial debug( _rxpin, _txpin ); // RX, TX

#define SSID "network_name_here"
#define PASS "network_password_here"
#define IP "184.106.153.149" // ThingSpeak IP Address: 184.106.153.149
String GET = "GET /update?key=your_thinspeak_write_api_key";

void setup() {
Serial.begin( _baudrate );
  debug.begin( _baudrate );
  sendDebug("AT");
  delay(5000);
  if(Serial.find("OK"))
  {
    debug.println("RECEIVED: OK\nData ready to sent!");
    connectWiFi();
  }


}

void loop() {
  value_temp = analogRead(sensor_temp);
  Serial.print("temperature");
  Serial.println( value_temp );
  value_light = analogRead(sensor_light);
  Serial.print("light");
  Serial.println( value_light );
  value_water = analogRead(sensor_water);
  Serial.print("water");
  Serial.println( value_water );
  String temp =String(value_temp);// turn integer to string
  String light= String(value_light);// turn integer to string
  String water=String(value_water);// turn integer to string
  updateTS(temp,light, water);
  delay(5000); //added delay here
}

//----- update the Thingspeak string with 3 values
void updateTS( String T, String H , String W)
{
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  sendDebug(cmd);
  delay(2000);
  if( Serial.find( "Error" ) )
  {
    debug.print( "RECEIVED: Error\nExit1" );
    return;
  }

  cmd = GET + "&field1=" + T +"&field2=" + H +"&field3=" + W +"\r\n";
  Serial.print( "AT+CIPSEND=" );
  Serial.println( cmd.length() );
  if(Serial.find( ">" ) )
  {
    debug.print(">");
    debug.print(cmd);
    Serial.print(cmd);
  }
  else
  {
    sendDebug( "AT+CIPCLOSE" );
  }
  if( Serial.find("OK") )
  {
    debug.println( "RECEIVED: OK" );
  }
  else
  {
    debug.println( "RECEIVED: Error\nExit2" );
  }
}

void sendDebug(String cmd)
{
  debug.print("SEND: ");
  debug.println(cmd);
  Serial.println(cmd);
}

boolean connectWiFi()
{
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  sendDebug(cmd);
  delay(5000);
  if(Serial.find("OK"))
  {
    debug.println("RECEIVED: OK");
    return true;
  }
  else
  {
    debug.println("RECEIVED: Error");
    return false;
  }

  cmd = "AT+CIPMUX=0";
  sendDebug( cmd );
  if( Serial.find( "Error") )
  {
    debug.print( "RECEIVED: Error" );
    return false;
  }
}

